package org.Agenty2012.Agent;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;

import android.app.IntentService;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationManager;
import android.os.IBinder; 
import android.os.RemoteException;
import android.util.Log;

//06-18 13:27:56.964: W/ActivityManager(59): Unable to start service Intent { cmp=org.Agenty2012.Agent/.GpsService (has extras) }: not found

public class GpsService extends Service{
	private static boolean goOn = false;
	//public GpsService() {
	//	super("GpsService");
	//	// TODO Auto-generated constructor stub
	//}

	private String sid;
	private String address;
	private MyLocationListener listener;
	@Override
	public IBinder onBind(Intent arg0) {
		Log.d(getClass().getSimpleName(), "onBind()");
		sid = arg0.getStringExtra("sid");
		address = arg0.getStringExtra("address");
		return null;
	}  

	
	@Override
	public void onDestroy() {
		super.onDestroy();
		goOn = false;
		LocationManager locationManager = (LocationManager) getApplicationContext().getSystemService(Context.LOCATION_SERVICE);
		locationManager.removeUpdates(listener);
		Log.d(getClass().getSimpleName(),"onDestroy()");
	}
	
	@Override
	public int onStartCommand(Intent intent, int flags, int startid) {  
		address = intent.getStringExtra("address");
		sid = intent.getStringExtra("sid");
		goOn = true;
		LocationManager locationManager = (LocationManager) getApplicationContext().getSystemService(Context.LOCATION_SERVICE);
		Criteria criteria = new Criteria();
		criteria.setAccuracy(Criteria.ACCURACY_FINE);
		String provider = locationManager.getBestProvider(criteria, true);
		
		listener = new MyLocationListener(sid, address);
		locationManager.requestLocationUpdates(provider, 3000, 2, listener);
		
	    return START_STICKY;
	}

/*	
	@Override
	public void onHandleIntent(Intent intent) {
		//super.onStart(intent);
		goOn = !goOn;
		sid = intent.getStringExtra("sid");
		Log.d(getClass().getSimpleName(), "onStart()");
		Random generator = new Random();
		while (goOn){
            double lat = (generator.nextDouble() * 0.02) - 0.01 + 50.06;
            double lon = (generator.nextDouble() * 0.02) - 0.01 + 19.91;
            postData(sid, lat, lon);
            try {
				Thread.sleep(1500);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}
	*/


    public void postData(String sid, double lat, double lon) {
        // Create a new HttpClient and Post Header
    	//String baseUrl = "http://10.0.2.2:1785/Locations.asmx";
    	String baseUrl = address + "/Locations.asmx";
        HttpClient httpclient = new DefaultHttpClient();
        HttpPost httppost = new HttpPost(baseUrl+"/AddLocation");// + "?nickname=" + name + "&color=" + color);
 
        try {
            // Add your data
            List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(3);
            nameValuePairs.add(new BasicNameValuePair("sid", sid));
            nameValuePairs.add(new BasicNameValuePair("lat", String.valueOf(lat)));
            nameValuePairs.add(new BasicNameValuePair("lon", String.valueOf(lon)));
            httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
            httppost.setHeader("Content-type", "application/x-www-form-urlencoded");

            // Execute HTTP Post Request
            HttpResponse response = httpclient.execute(httppost);
            if (response != null)
            	Log.d(getClass().getSimpleName(),"otrzymal odpowiedz");
           // String s = inputStreamToString(response.getEntity().getContent()).toString();
           // String ss = "tomek";
            
        } catch (ClientProtocolException e) {
            // TODO Auto-generated catch block
        } catch (IOException e) {
            // TODO Auto-generated catch block
        }
    }
    
    private StringBuilder inputStreamToString(InputStream is) {
        String line = "";
        StringBuilder total = new StringBuilder();
        
        // Wrap a BufferedReader around the InputStream
        BufferedReader rd = new BufferedReader(new InputStreamReader(is));

        // Read response until the end
        try {
			while ((line = rd.readLine()) != null) { 
			    total.append(line); 
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
        
        // Return full string
        return total;
    }

}